/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.CA_Service;
import model.KeyIO;
import sun.security.x509.X509CertInfo;

/**
 *
 * @author XuanTuan
 */
public class AuthenticateCertControl extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");


        MultipartRequest mt = null;
        String encType = "utf-8";
        String folder = getServletContext().getRealPath("\\AuthenticateCert");
        int maxSize = 5 * 1024 * 1024;


        mt = new MultipartRequest(request, folder, maxSize, encType, new DefaultFileRenamePolicy());
        String filePath = folder + "\\" + mt.getParameter("filename");

        System.out.println("file path: " + filePath);

        //get cert
        boolean verify = false, revoke = false, validate = false;
        FileInputStream cert = null, crl = null;
        PrivateKey privateKey = null;
        try {
            cert = new FileInputStream(filePath);
            PublicKey publicKey = KeyIO.getPublicKey(new FileInputStream(getServletContext().getRealPath("\\CAKeys") + "\\pub"));
            privateKey = KeyIO.getPrivateKey(new FileInputStream(getServletContext().getRealPath("\\CAKeys") + "\\pri"));
            verify = CA_Service.verifyCert(new FileInputStream(filePath), publicKey);
//            System.out.println(cert.available());
            cert = new FileInputStream(filePath);
            validate = CA_Service.validateCert(new FileInputStream(filePath));
        } catch (Exception ex) {
            request.setAttribute("info", "<font color=\"red\">Your file that uploaded is not a certificate!</font>");
        }

        if (verify == false) {
            request.setAttribute("info", "<font color=\"red\">This Certificate is not create by our organization!</font>");
        } else if (validate == false) {
            request.setAttribute("info", "<font color=\"red\">This Certificate was expired!</font>");
        } else {
            try {
                crl = new FileInputStream(getServletContext().getRealPath("\\CRL") + "\\crl.crl");
                cert = new FileInputStream(filePath);
                revoke = CA_Service.isRevoke(new FileInputStream(filePath), crl, privateKey);
                crl.close();
                if (revoke == true) {
                    request.setAttribute("info", "<font color=\"red\">This Certificate was revoked!</font>");
                } else {
                    request.setAttribute("info", "<font color=\"green\">This Certificate is valid!</font>");
                }
            } catch (Exception ex) {
                request.setAttribute("info", "<font color=\"green\">This Certificate is valid!</font>");
            }
        }

        //delete file
        cert.close();
        new File(filePath).delete();




        RequestDispatcher dispatcherObject = getServletContext().getRequestDispatcher("/info.jsp");
        dispatcherObject.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
